package cn.shanke.torrentmanagerserver.util;

import cn.shanke.torrentmanagerserver.dao.BTSiteMapper;
import cn.shanke.torrentmanagerserver.dao.CategoryMapper;
import cn.shanke.torrentmanagerserver.model.BTSite;
import cn.shanke.torrentmanagerserver.model.Category;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@DependsOn("applicationContextUtil")
public class CacheUtil {
    public static final String CACHE_VALUE_CONSTANTS = "constants";

    public static final String KEY_PATH_OF_BTSITE = "pathOfSite-";
    public static final String KEY_PATH_OF_CATEGORY = "pathOfCategory-";

    private BTSiteMapper btSiteMapper = ApplicationContextUtil.getBean(BTSiteMapper.class);
    private CategoryMapper categoryMapper = ApplicationContextUtil.getBean(CategoryMapper.class);

    @Cacheable(value = CACHE_VALUE_CONSTANTS ,key = "'" + KEY_PATH_OF_BTSITE + "'+#p0")
    public String getPathOfBTSite(Long id) {
        String path = null;
        BTSite model = btSiteMapper.selectById(id);
        if (model != null) {
            path = model.getFolder();
        }
        if (StringUtils.hasText(path)) {
            path = "";
        } else {
            path = "/" + path;
        }
        return path;
    }

    @Cacheable(value = CACHE_VALUE_CONSTANTS ,key = "'" + KEY_PATH_OF_CATEGORY + "'+#p0")
    public String getPathOfCategory(Long id) {
        String path = null;
        Category model = categoryMapper.selectById(id);
        if (model != null) {
            path = model.getFolder();
        }
        if (StringUtils.hasText(path)) {
            path = "";
        } else {
            path = "/" + path;
        }
        return path;
    }
}
